<?php

namespace app\admin\controller\wanlshop;

use app\admin\model\Area;
use app\api\controller\wanlshop\Separate;
use app\api\model\wanlshop\GoodsSku;
use app\api\model\wanlshop\GoodsSpu;
use app\api\model\wanlshop\Industry;
use app\common\controller\Wanlshop;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\controller\Backend;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class Yiyatong extends Backend
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    protected $model = null;
    protected $appKey = '1826512647411253249';
    protected $appSecret = '3575603d8bc9c79ff9ef93f54056124f';

    protected $version = '1.0';
    protected $http = 'https://sce-opz.changecloud.cn';
    public function _initialize()
    {
        parent::_initialize();
    }
    // 生成随机数
    private function generateRandomNumber()
    {
        // 生成两个较小的随机数并拼接，确保最终的长度为19位
        $part1 = rand(1000000000, 9999999999); // 10位数
        $part2 = rand(100000000, 999999999);   // 9位数
        return (string)$part1 . (string)$part2;
    }

    // 获取当前时间戳（精确到毫秒）
    private function getCurrentTimeMillis()
    {
        return round(microtime(true) * 1000);
    }
    // 拼接查询字符串
    private function buildQueryString($params)
    {
        $queryString = '';
        foreach ($params as $key => $value) {
            // 处理数组类型数据
            if (is_array($value)) {
                $value = json_encode($value, JSON_UNESCAPED_UNICODE); // 保持中文字符不转义
            }
            $queryString .= $key . '=' . $value . '&';
        }
        return rtrim($queryString, '&'); // 去掉最后一个多余的 &
    }
    // 生成签名的函数
    private function generateSign($params)
    {
        // 1. 排除 sign 字段
        unset($params['sign']);

        // 2. 按照键名 ASCII 码升序排序
        ksort($params);

        // 3. 拼接参数名和参数值
        $queryString = $this->buildQueryString($params);

        // 4. 拼接 appSecret
        $queryString .= '&' . $this->appSecret;

        // 5. 生成 MD5 签名
        return md5($queryString);
    }
    public function sendRequest($url, $method, $params)
    {
        // 构建请求头数据
        $headerParams = [
            'appKey' => $this->appKey,
            'randomNumber' => $this->generateRandomNumber(),
            'timeStamp' => $this->getCurrentTimeMillis(),
            'version' => $this->version,
        ];

        // 合并请求头和接口参数
        $allParams = array_merge($headerParams, $params);

        // 生成签名
        $sign = $this->generateSign($allParams);

        // 将签名放入请求头
        $headerParams['sign'] = $sign;

        // 设置请求头
        $headers = [
            'Content-Type: application/json',
            'appKey: ' . $this->appKey,
            'randomNumber: ' . $headerParams['randomNumber'],
            'timeStamp: ' . $headerParams['timeStamp'],
            'version: ' . $this->version,
            'sign: ' . $sign
        ];

        // 初始化 curl
        $ch = curl_init();
        // 判断请求类型并设置 curl 选项
        if (strtoupper($method) == 'POST') {
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            // 处理空参数时传递空的 JSON 对象
            if (empty($params)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, '{}');
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
            }
        } else if (strtoupper($method) == 'GET') {
            $queryString = $this->buildQueryString($params);
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $queryString);
        }

        // 设置 curl 其他选项
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 如果是 https 请求

        // 执行请求并获取响应
        $response = curl_exec($ch);

        // 检查是否有错误
        if (curl_errno($ch)) {
            return 'Curl error: ' . curl_error($ch);
        }

        // 关闭 curl
        curl_close($ch);

        // 返回响应结果
        return $response;
    }
    //获取分类
    public function yyt_type()
    {
        $params = $this->request->param();

        // 处理一级分类数据
        $list = \app\admin\model\wanlshop\Category::where('type','goods')->where('level',2)->select();
        foreach ($list as $item){
            // 定义请求 URL
            $url = $this->http . '/scce/cmc/cmc/spu/open/getCategorys';
            $params = ['id' => $item['id']];
            // 选择请求方式：GET 或 POST
            $method = 'POST';

            // 调用 sendRequest 发送请求
            $response = $this->sendRequest($url, $method, $params);
            $response = json_decode($response,true);
            foreach ($response['data'] as $datum){
                $cate = \app\admin\model\wanlshop\Category::where('id', $datum['id'])->find();
                if ($cate) {
                    // 如果找到，更新记录
                    $cate->id = $datum['id'];
                    $cate->pid = $item['id']; // 更新父级 ID
                    $cate->type = 'goods';
                    $cate->name = $datum['name'];
                    $cate->weigh = 1;
                    $cate->level = 3;
                    $cate->save();
                } else {
                    // 如果未找到，创建新的记录
                    \app\admin\model\wanlshop\Category::create([
                        'id' => $datum['id'],
                        'pid' => $item['id'], // 设置父级 ID
                        'type' =>'goods',
                        'name' => $datum['name'],
                        'weigh' => 1,
                        'level' => 3,
                    ]);
                }
            }
        }
        $result = array("data"=>$response['data'], "status" => 0,'msg'=>'成功');

        return json($result);
    }

    //商品列表
    public function getSpuIdList()
    {
        $params = $this->request->param();
        $page = 11;
        $pages = 12;
        $num = 0;

        do{

            $params['pageIndex'] = $page;
            $params['pageSize'] = 400;
            // 定义请求 URL
            $url = $this->http . '/scce/cmc/cmc/spu/open/getSpuIdList';
            $method = 'POST';
            $response = $this->sendRequest($url, $method, $params);
            $response = json_decode($response,true);
            $data = $response['data']['spuIdList'];

            foreach ($data as $spuID){

                $url = $this->http . '/scce/cmc/cmc/spu/open/getSpuBySpuIds';
                $method = 'POST';
                $SpuIds = $this->sendRequest($url, $method, ['spuIdList'=>[$spuID]]);
                $SpuIds = json_decode($SpuIds,true);
                $spuId = $SpuIds['data'][0];
                $url = $this->http . '/scce/cmc/cmc/spu/open/listSkuBySpuId';
                $guige = $this->sendRequest($url, $method, ['spuId'=>$spuID]);
                $guige = json_decode($guige,true);
                $guige = $guige['data'];
                $good = \app\admin\model\wanlshop\Goods::where('id', $spuID)->find();
                $carouselImgList = $spuId['carouselImgList'];  // 获取数组
                $carouselImgString = implode(',', $carouselImgList);  // 用逗号拼接成字符串
                if ($good) {
                    // 如果找到，更新记录
                    $good->id = $spuID;
                    $good->shop_category_id = $spuId['categoryId3']; // 更新父级 ID
                    $good->shop_id = 154;
                    $good->category_id = $spuId['categoryId3'];
                    $good->brand_id = $spuId['brandId'];
                    $good->title = $spuId['name'];
                    $good->image = $spuId['detailImgList'][0];
                    $good->images = $carouselImgString;
                    $good->description = $spuId['name'];
                    $good->content = $spuId['description']??$spuId['name'];
                    $good->specs = count($guige)>1?'multi':'single';
                    $good->weigh = 1;
                    $good->status = 'hidden';
                    $good->save();

                } else {
                    // 如果未找到，创建新的记录
                    \app\admin\model\wanlshop\Goods::create([
                        'id' => $spuID,
                        'shop_id' => 154, // 设置父级 ID
                        'shop_category_id' => $spuId['categoryId3'],
                        'category_id' => $spuId['categoryId3'],
                        'brand_id' => $spuId['brandId'],
                        'title' => $spuId['name'],
                        'image' => $spuId['detailImgList'][0],
                        'images' => $carouselImgString,
                        'description' => $spuId['name'],
                        'content' => $spuId['description']??$spuId['name'],
                        'specs' => count($guige)>1?'multi':'single',
                        'weigh'=>1,
                        'status'=>'hidden',
                    ]);
                }
                GoodsSku::where('goods_id',$spuID)->delete();
                $guigeName = '';
                foreach ($guige as &$guigeData){
                    $url = $this->http . '/scce/cmc/cmc/spu/open/goods/findSkuSalePrice';
                    $price = $this->sendRequest($url, $method, ['skuIds'=>$guigeData['skuId']]);
                    $price = json_decode($price,true);
                    $guigeData['price'] = $price['data'][0];
                    $name = '';
                    foreach ($guigeData['skuPropertyList'] as $guigeDatum){
                        $name .= $guigeDatum['specValueName'];
                    }
                    if (!empty($guigeName)) {
                        $guigeName .= ',';  // 在已有的guigeName后面加逗号
                    }
                    $guigeName .= $name;
                    GoodsSku::create([
                        'goods_id'=>$spuID,
                        'difference'=>$name,
                        'market_price'=>$guigeData['price']['officialDistriPrice'],
                        'price'=>$guigeData['price']['retailPrice'],
                        'stock'=>$guigeData['stock'],
                        'weigh'=>$spuId['weight']?$spuId['weight']:1,
                        'sn'=>$guigeData['skuId'],

                    ]);
                }
                GoodsSpu::where('goods_id',$spuID)->delete();
                GoodsSpu::create([
                    'goods_id'=>$spuID,
                    'name'=>'规格',
                    'item'=>$guigeName,
                ]);

                $good=  \app\admin\model\wanlshop\Goods::where('id',$spuID)->find();
                $good->price = $guige[0]['price']['retailPrice'];
                $good->save();
                $num++;
            }
//            $page++;
        } while ($page < $pages);

        $result = array("data"=>$num, "status" => 0,'msg'=>'成功');
        return json($result);
    }
    //商品详情

    //导入品牌
    public function getBrands()
    {
        $params = $this->request->param();
        $page = 2400;
        $params['pageIndex'] = $page;
        $totalProcessed = 0;
        // 定义请求 URL
        $url = $this->http . '/scce/cmc/cmc/spu/open/getBrands';
        // 选择请求方式：POST
        $method = 'POST';
        do {
            // 调用 sendRequest 发送请求
            $params['pageIndex'] = $page; // 设置当前页码
            $response = $this->sendRequest($url, $method, $params);
            $response = json_decode($response, true);

            // 获取分页数据
            $pages = $response['data']['pages']; // 总页数
            $records = $response['data']['records']; // 当前页记录

            // 将每条记录插入或更新到数据库，并更新计数器
            foreach ($records as $datum) {
                $brand = \app\admin\model\wanlshop\Brand::where('id', $datum['id'])->find();
                if ($brand) {
                    // 如果找到，更新记录
                    $brand->id = $datum['id'];
                    $brand->admin_id = 0; // 更新父级 ID
                    $brand->shop_id = 154;
                    $brand->name = $datum['name'];
                    $brand->image = $datum['logoPath'];
                    $brand->content = $datum['name'];
                    $brand->state = 1;
                    $brand->weigh = 1;
                    $brand->save();
                } else {
                    // 如果未找到，创建新的记录
                    \app\admin\model\wanlshop\Brand::create([
                        'admin_id' => 0,
                        'id' => $datum['id'],
                        'shop_id' => 154, // 设置父级 ID
                        'name' => $datum['name'],
                        'image' => $datum['logoPath'],
                        'content' => $datum['name'],
                        'weigh' => 1,
                        'state' => 1,
                    ]);
                }
                // 每处理一条记录，计数器加1
                $totalProcessed++;
            }

            // 递增页码
            $page++;

        } while ($page <= 2500); // 继续循环直到处理完所有页

        // 返回总共处理的记录数
        $result = array("total_processed" => $totalProcessed, "status" => 0, 'msg' => '成功');
        return json($result);
    }
    //导入地区
    public function getRegionByCodeOpen()
    {
        $params = $this->request->param();

        $url = $this->http . '/scce/pbc/pbc/region/getRegionByCodeOpen';
        $method = 'POST';
        $response = $this->sendRequest($url, $method, $params);
        $response = json_decode($response,true);

        // 处理一级地区数据
        $this->processCodes($response['data']);
        $result = array("status" => 0, 'msg' => '成功');
        return json($result);
    }
    private function processCodes($codes, $parentId = 0)
    {
        foreach ($codes as $item) {
            // 处理当前分类
            $area = Area::where('id', $item['id'])->find();
            if ($area) {
                // 如果找到，更新记录
                $area->id = $item['id'];
                $area->pid = $parentId; // 更新父级 ID
                $area->shortname = $item['name'];
                $area->name = $item['name'];
                $area->mergename = $item['regionFullName'];
                $area->level = $item['regionLevel'];
                $area->code = $item['regionCode'];
                $area->lng = $item['longitude'];
                $area->lat = $item['latitude'];
                $area->save();
            } else {
                // 如果未找到，创建新的记录
                Area::create([
                    'id' => $item['id'],
                    'pid' => $parentId,
                    'shortname' => $item['name'],
                    'name' => $item['name'],
                    'mergename' => $item['regionFullName'],
                    'level' => $item['regionLevel'],
                    'code' => $item['regionCode'],
                    'lng' => $item['longitude'],
                    'lat' => $item['latitude'],
                ]);
            }
//
//            // 请求并处理二级分类
//            if (isset($item['id'])) {
//
//                $this->fetchAndProcessSubCodes($item['id'],$item['regionCode']);
//            }
        }
    }
    public function fetchAndProcessSubCodes()
    {
        $area = Area::where('level',2)->select();

        foreach ($area as $item) {
//            $regionCode[] = $item['code']; // 将每个 item 的 code 加入数组
            // 定义请求 URL，用于获取子分类
            $url = $this->http . '/scce/pbc/pbc/region/getRegionByCodeOpen';

            // 设置请求参数
            $params = ['regionCode' => $item['code']];
            $method = 'POST'; // 根据实际情况选择请求方式

            // 发送请求获取子分类数据
            $response = $this->sendRequest($url, $method, $params);
            $response = json_decode($response, true);
            foreach ($response['data'] as $datum){
                $area = Area::where('id', $datum['id'])->find();
                if ($area) {
                    // 如果找到，更新记录
                    $area->id = $datum['id'];
                    $area->pid = $item['id']; // 更新父级 ID
                    $area->shortname = $datum['name'];
                    $area->name = $datum['name'];
                    $area->mergename = $datum['regionFullName'];
                    $area->level = $datum['regionLevel'];
                    $area->code = $datum['regionCode'];
                    $area->lng = $datum['longitude'];
                    $area->lat = $datum['latitude'];
                    $area->save();
                } else {
                    // 如果未找到，创建新的记录
                    Area::create([
                        'id' => $datum['id'],
                        'pid' => $item['id'],
                        'shortname' => $datum['name'],
                        'name' => $datum['name'],
                        'mergename' => $datum['regionFullName'],
                        'level' => $datum['regionLevel'],
                        'code' => $datum['regionCode'],
                        'lng' => $datum['longitude'],
                        'lat' => $datum['latitude'],
                    ]);
                }
            }
        }

    }

    //查询运费
    public function calculate($data)
    {

        $url = $this->http . '/scce/cmc/cmc/freight/calculate';

        $method = 'POST';
        $response = $this->sendRequest($url, $method, $data);
        $response = json_decode($response,true);
        return $response['data'];
    }
    //创建订单
    public function submitOrder()
    {
        $params = $this->request->param();
        $url = $this->http . '/scce/ctc/ctc/reseller/order/submitOrder';
        $method = 'POST';
        $response = $this->sendRequest($url, $method, $params);
        return $response['data'];
    }

}
